package com.ztwo.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ztwo.ssm.common.Constant;
import com.ztwo.ssm.pojo.Book;
import com.ztwo.ssm.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author ZTwo
 * @Date 2022/6/15 21:14
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;

    @RequestMapping("/allBook")
    public String list(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, Model model) {
        PageHelper.startPage(pageNo, Constant.PAGE_SIZE);
        List<Book> books = bookService.queryAllBook();

        PageInfo pageInfo = new PageInfo(books);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("list", pageInfo.getList());
        return "allBook";
    }

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addPaper(Book book) {
        System.out.println(book);
        bookService.addBook(book);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
        Book book = bookService.queryBookById(id);
        System.out.println(book);
        model.addAttribute("book", book);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Model model, Book book) {
        System.out.println(book);
        bookService.updateBook(book);
        Book books = bookService.queryBookById(book.getBookID());
        model.addAttribute("Book", books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,
                            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                            Model model) {
        PageHelper.startPage(pageNo, Constant.PAGE_SIZE);
        List<Book> books = bookService.queryBookByName(queryBookName.trim());
        PageInfo<Book> pageInfo = new PageInfo<>(books);

        if (books.size() == 0) {
            model.addAttribute("error", "没有找到本书！");
        }

        model.addAttribute("list", pageInfo.getList());
        model.addAttribute("pageInfo", pageInfo);
        return "allBook";
    }

}
